package com.lagou.cofig;


import com.lagou.io.Resources;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import lagou.io.pojo.Configuration;
import org.dom4j.Document;

import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法就是降配置文件进行解析，封装Configuration
     */
    public Configuration parseConfigura( InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        Properties properties = new Properties();
        List<Element> list = rootElement.selectNodes("//property");
        List<Element> list1 = rootElement.selectNodes("//mapper");
        for (Element o : list1) {
            String mapperPath = o.attributeValue("resource");
            InputStream input = Resources.getResourceAsSteam(mapperPath);
            XmlMapperBuild xmlMapperBuild = new XmlMapperBuild(configuration);
            xmlMapperBuild.pase(input);

        }
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("direrClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        configuration.setDataSource(comboPooledDataSource);
        return configuration;
    }
}
